import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @author trungsi
 *
 */
public class Diff {
	def srcDir, localDir, diffDir
	
	File srcDirFile, localDirFile, diffDirFile
	
	Diff(srcDir, localDir, diffDir) {
		this.srcDir = srcDir
		this.localDir = localDir
		this.diffDir = diffDir
		resolvePaths()
	}
	
	public void doDiff() {
		//resolvePaths()
		doDiffDir(srcDirFile)
		
		doDiffDeleted(localDirFile)
	}

	def resolvePaths() {
		srcDirFile = new File(srcDir)
		localDirFile = new File(localDir)
		diffDirFile = new File(diffDir)
	}
	
	private doDiffDeleted(baseDirFile) {
		baseDirFile.eachFile {localFile ->
			if (localFile.isFile()) {
				if ( !new File(srcDirFile, localFile.absolutePath - localDirFile.absolutePath).exists() ) {
					localFile.delete()

					def deletedFile = new File(diffDirFile, localFile.absolutePath - localDirFile.absolutePath + '.deleted')
					// force mkdirs
					deletedFile.getParentFile().mkdirs()
					deletedFile.createNewFile()
				}
			} else {
				doDiffDeleted(localFile)
			}
		}
	}

	private doDiffDir(baseDirFile) {
		baseDirFile.eachFile {file ->
			if (file.isFile()) {
				def localFile = getLocalFile(file)
				if ( !localFile.exists() ) {
					copyFile(file, localFile)
	
					copyFile(file, new File(diffDirFile, file.absolutePath - srcDirFile.absolutePath + '.added'))
				} else if (localFile.lastModified() < file.lastModified()) {
					localFile.delete()
					copyFile(file, localFile)
	
					def diffFile = new File(diffDirFile, file.absolutePath - srcDirFile.absolutePath)
					diffFile.delete()
					copyFile(file, diffFile)
				}
			} else {
				doDiffDir(file)
			}
		}
	}

	def getLocalFile(File file) {
		new File(localDirFile, file.absolutePath - srcDirFile.absolutePath)
	}

	static def replacePath(String path, token, replace) {
		path.replace(token, replace)
	}
	
	static def copyFile(File file, File toFile) {
		// force mkdirs
		toFile.getParentFile().mkdirs()
		Files.copy(file.toPath(), toFile.toPath(), StandardCopyOption.COPY_ATTRIBUTES)
	}
	
	static void main(args) {
		def diff = new Diff('C:/Users/trungsi/workspace2/cores-trunk/front-office/web/src', 'test-dir/local-dir', 'test-dir/diff-dir')
		diff.doDiff()
	}
}

